import CryptoJS from 'crypto-js';

export const decryptStr = (data) => {
  let firstSlashIndex = data.indexOf("/");
  let ivSourceKey = data.substr(0, firstSlashIndex);
  let base64Data = data.substr(firstSlashIndex + 1);
  let mergeKey = ivSourceKey.substr(0, 1);
  ivSourceKey = ivSourceKey.substr(1);
  let ivKey = ivSourceKey.replace(/\d/g, mergeKey);
  //console.log(ivSourceKey, ivKey, mergeKey);
  let decrypt = CryptoJS.AES.decrypt(base64Data, CryptoJS.enc.Latin1.parse(ivSourceKey), {
    iv: CryptoJS.enc.Latin1.parse(ivKey),
    padding: CryptoJS.pad.ZeroPadding
  });
  return JSON.parse(decrypt.toString(CryptoJS.enc.Utf8));
}

export const encryptStr = (data) => {
  let ivSourceKey = randomString(16);
  let mergeKey = randomString(1);
  let ivKey = ivSourceKey.replace(/\d/g, mergeKey);
  // console.log(ivSourceKey, ivKey, mergeKey);
  let decrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Latin1.parse(ivSourceKey), {
    iv: CryptoJS.enc.Latin1.parse(ivKey),
    padding: CryptoJS.pad.ZeroPadding
  });
  return `${mergeKey}${ivSourceKey}/${decrypted}`;
}

export const encryptParams = (data) => {
  if (isObjectOrArray(data)) {
    data = JSON.stringify(data).replaceAll("\"", "\\\"");
  }
  // console.log("encryptParams", data);
  let ivSourceKey = randomString(16);
  let mergeKey = randomString(1);
  let ivKey = ivSourceKey.replace(/\d/g, mergeKey);
  // console.log(ivSourceKey, ivKey, mergeKey);
  let decrypted = CryptoJS.AES.encrypt(`{"txt":"${data}","t":${new Date().getTime() + 3000}}`, CryptoJS.enc.Latin1.parse(ivSourceKey), {
    iv: CryptoJS.enc.Latin1.parse(ivKey),
    padding: CryptoJS.pad.ZeroPadding
  });
  // console.log(decrypted.toString());
  return `${mergeKey}${ivSourceKey}/${decrypted}`;
}

function randomString(length) {
  let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
  let maxPos = chars.length;
  let code = '';
  for (let i = 0; i < length; i++) {
    code += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return code;
}

function isObjectOrArray(variable) {
  return typeof variable === 'object' && (Array.isArray(variable) || Object.prototype.toString.call(variable) !== '[object Array]');
}
